﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;


namespace PersistentObject.Common.DataConvertors
{
    /// <summary>
    /// Represent an Image convertor using byte[] to store data
    /// </summary>
    public class ImageConvertor : DataConvertor
    {
        public ImageConvertor()
        {
        }

        public override DbType GetDbType()
        {
            return DbType.Binary;
        }
        
        public override object PersistFrom(object ClrObject)
        {
            if (ClrObject == null) return null;
            if(ClrObject is Image)
            {
                MemoryStream ms = new MemoryStream();
                (ClrObject as Image).Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                byte[] bytes = ms.ToArray();
                return bytes;
            }
            return null;
        }

        public override object RetrieveFrom(object PersistentObject)
        {
            if (PersistentObject == null) return null;
            if (PersistentObject == DBNull.Value) return null;
            if (PersistentObject is byte[])
            {
                try
                {
                    MemoryStream ms = new MemoryStream((PersistentObject as byte[]));
                    Image returnImage = Image.FromStream(ms);
                    return returnImage;
                }
                catch
                {
                    return null;
                }
            }
            return null;
        }
    }
}
